package com.fudan.backend.controller;

import com.fudan.backend.exception.RetCode;
import com.fudan.backend.pojo.Address;
import com.fudan.backend.service.AddressService;
import com.fudan.backend.util.JwtUtil;
import com.fudan.backend.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    AddressService addressService;

    @GetMapping("/{addressId}")
    public R getAddressByAddressId(@PathVariable("addressId") String addressId, @RequestHeader String token) {
        String userId = JwtUtil.getUserId(token);
        Address address = addressService.getAddressByAddressId(addressId, userId);
        return new R(RetCode.ADDRESS_SUCCESS, address);
    }

    @GetMapping("/default")
    public R getDefaultAddress(@RequestHeader String token) {
        String userId = JwtUtil.getUserId(token);
        Address add = addressService.getDefaultAddress(userId);
        return new R(RetCode.ADDRESS_SUCCESS, add);
    }

    @GetMapping("/user")
    public R getAllUserAddress(@RequestHeader String token) {
        String userId = JwtUtil.getUserId(token);
        List<Address> addList = addressService.getAllUserAddress(userId);
        return new R(RetCode.ADDRESS_SUCCESS, addList);
    }

    @PostMapping("/set-default/{addressId}")
    public R setDefaultAddress(@PathVariable("addressId") String addressId, @RequestHeader String token) {
        String userId = JwtUtil.getUserId(token);
        RetCode retCode = addressService.changeDefaultAddress(addressId, userId);
        return new R(retCode);
    }

    @PostMapping("/modify")
    public R modifyAddress(@RequestBody Address address, @RequestHeader String token) {
        String userId = JwtUtil.getUserId(token);
        RetCode retCode = addressService.changeAddress(address, userId);
        return new R(retCode);
    }

    @PostMapping("/add")
    public R addAddress(@RequestBody Address address, @RequestHeader String token) {
        String userId = JwtUtil.getUserId(token);
        RetCode retCode = addressService.addAddress(address, userId);
        return new R(retCode);
    }
    @PostMapping("/delete/{addressId}")
    public R deleteAddress(@PathVariable("addressId") String addressId, @RequestHeader String token){
        String userId = JwtUtil.getUserId(token);
        RetCode retCode = addressService.deleteAddress(addressId, userId);
        return new R(retCode);

    }
}
